package com.ccom.user.controller;

import com.ccom.api.domain.User;
import com.ccom.api.dto.ResetPasswordDto;
import com.ccom.api.dto.UserSaveDto;
import com.ccom.api.vo.UserVo;
import com.ccom.core.common.constant.ServiceNameConstants;
import com.ccom.core.common.enums.ExceptionEnums;
import com.ccom.core.common.model.Result;
import com.ccom.core.common.util.BeanUtils;
import com.ccom.core.common.util.PasswordUtil;
import com.ccom.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * @Description
 * @Author zjj
 * @Date 2021/8/25
 */
@Slf4j
@Api(tags = "用户controller")
@RestController
@RequestMapping(ServiceNameConstants.USER_SERVICE_URL_PREFIX + "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("保存用户")
    @PostMapping("/save")
    public Result saveUser(@RequestBody UserSaveDto dto) {
        if(dto.checkAndSetUserName()){
            Result.remind(ExceptionEnums.USER_PASSWORD_NAME_ERROR);
        }
        User user = BeanUtils.copy(dto, User.class);
        user.initUser();
        String password = user.getPassword();
        user.setPassword(PasswordUtil.encrypt(user.getUserName(), password, user.getSalt()));
        userService.saveUser(user);
        return Result.success();
    }

    @ApiOperation("删除用户")
    @GetMapping("/delete")
    public Result deleteUserById(@RequestParam(value = "userId") @NotNull String userId) {
        userService.deleteUser(userId);
        return Result.success();
    }

    @ApiOperation("根据用户名获取用户信息")
    @GetMapping("/getUserByName")
    public Result<UserVo> getUserByName(@RequestParam(value = "userName") @NotNull String userName) {
        User user = userService.getUserByName(userName);
        UserVo userVo = BeanUtils.copy(user, UserVo.class);
        return Result.date(userVo);
    }

    @ApiOperation("根据用户id获取用户信息")
    @GetMapping("/getUserByUserId")
    public Result<UserVo> getUserByUserId(@RequestParam(value = "userId") @NotNull String userId) {
        User user = userService.getById(userId);
        UserVo userVo = BeanUtils.copy(user, UserVo.class);
        return Result.date(userVo);
    }

    @ApiOperation("获取所有用户信息")
    @GetMapping("/getAllUser")
    public Result getAllUser() {
        return Result.date(userService.getAllUser());
    }

    @ApiOperation("重置密码")
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody @NotNull ResetPasswordDto dto) {
        boolean result = userService.resetPassword(dto.getUsername(), dto.getOldpassword(), dto.getNewpassword(), dto.getConfirmpassword());
        if (result) {
            return Result.success();
        }
        return Result.error("密码重置失败");
    }

}
